package com.sduept.nwld.dataserver.controller.dataview;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.primefaces.event.SelectEvent;

import com.sduept.generator.ObjectId;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.nwld.dataserver.manager.cim.PrimaryDeviceCountPersistenceManager;
import com.sduept.nwld.dataserver.manager.cim.PrimaryDeviceCountQueryManager;
import com.sduept.cim.ledger.total.model.PrimaryDeviceCount;
import com.sduept.utils.DateUtil;

/**
 * 一设备统计Controller
 *
 */

@Named
@ViewScoped
public class PrimaryDeviceCountController extends AbstractController{
	private static final long serialVersionUID = 4801720942776202905L;


	@Autowired
	private PrimaryDeviceCountQueryManager queryM;
	@Autowired
	private PrimaryDeviceCountPersistenceManager presistenceM;

	/**
	 * 当前年份设备数量信息
	 */
	private List<PrimaryDeviceCount> currentDeviceCounts = new ArrayList<PrimaryDeviceCount>();

	/**
	 * table
	 */
	private List<StatisticDeviceDto> statisticTableDto = new ArrayList<StatisticDeviceDto>();
	/**
	 * 调度电压等级
	 */
	private String[] selectedVoltage;
	private StatisticDeviceDto selectedDto;
	private String queryYear;
	private String updateTime;
	private List<Float> voltageLevels = new ArrayList<Float>();
	private Boolean reStatisticStatus = false;
	private Byte dispatchType = 0;
	private Byte unitType = 0;
	private Byte maintenanceType = 1;

	@PostConstruct
	public void init() {

		try {
			queryYear = String.valueOf(getCurrentYear()) ;
			voltageLevels = Arrays.asList(500.0f,220.0f,110.0f,35.0f);
			selectedVoltage = new String[] {"35","110","220","500"};
			initDeviceCountTable();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化一次设备统计表
	 * @throws ParseException
	 */
	private void initDeviceCountTable() throws ParseException {
		if(unitType == 0) {
			statisticTableDto  = initDispatchDeviceTable();
		}else {
			statisticTableDto  = initMaintenanceDeviceTable();
		}
	}

	/**
	 * 初始化检修范围Table
	 * @return
	 */
	private List<StatisticDeviceDto> initMaintenanceDeviceTable() {
		List<PrimaryDeviceCount> maintenanceList = queryM.findMaintenancePrimaryDeviceCount(getCurrentYear());
		if(maintenanceList.isEmpty()) {
			updateTime = DateUtil.getStringDate(new Date(), DateUtil.pattern_ymd);
			return new ArrayList<PrimaryDeviceCountController.StatisticDeviceDto>();
		}else {
			updateTime = DateUtil.getStringDate(maintenanceList.get(0).getStatisticTime(), DateUtil.pattern_ymd);
			List<StatisticDeviceDto>  list = filterTableDto(maintenanceList, maintenanceType);
			return list;
		}

	}

	/**
	 * 重新统计
	 * @throws ParseException
	 */
	public void  reStatistic() throws ParseException {
		selectedVoltage = null;
		presistenceM.persistenceDispatchStatisticCount(reStatisticStatus);
		presistenceM.persistenceMaintenanceStatisticCount(reStatisticStatus);
		if(unitType == 0) {
			statisticTableDto = resetDispatchDeviceDto();;
		}else if(unitType == 1){
			statisticTableDto =resetMaintenanceDeviceDto();
		}
	}
	/**
	 * 查询
	 */
	public void query() {
		if(unitType==0) {
			statisticTableDto =	dispatchQuery();
		}else if(unitType==1){
			statisticTableDto = maintenanceQuery();
		}
	}
	/**
	 * 多重查询 调度
	 */
	private List<StatisticDeviceDto>  dispatchQuery() {
		List<PrimaryDeviceCount> list;
		List<StatisticDeviceDto>  dtoList;
		if(Arrays.asList(selectedVoltage).contains("全部")||selectedVoltage==null) {
			list = queryM.findPrimaryDeviceCountByYear(Integer.valueOf(queryYear));
			dtoList = statisticTableDto(list, dispatchType);
		}else{
			list = queryM.findPrimaryDeviceCountByYearVoltage(Integer.valueOf(queryYear),selectedVoltage);
			dtoList = statisticTableDto(list,dispatchType);
		}
		return dtoList;
	}
	/**
	 * 多重查询 检修
	 * @return
	 */
	private  List<StatisticDeviceDto> maintenanceQuery() {
		List<PrimaryDeviceCount> list;
		List<StatisticDeviceDto>  dtoList;
		if(Arrays.asList(selectedVoltage).contains("全部")||selectedVoltage==null) {//电压等级包含全部或为空 只根据时间查 展示默认固定电压的值
			list = queryM.findPrimaryDeviceCountByYear(Integer.valueOf(queryYear));
			dtoList = statisticTableDto(list, maintenanceType);
		}else{
			list = queryM.findPrimaryDeviceCountByYearVoltage(Integer.valueOf(queryYear),selectedVoltage);
			dtoList = statisticTableDto(list,maintenanceType);
		}
		return dtoList;
	}
	/**
	 * 改变年份
	 */
	public void changeYear() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> map = context.getExternalContext().getRequestParameterMap();
		queryYear = map.get("yearAnalysis").toString();

	}

	public void onRowSelect(SelectEvent event){
		selectedDto = (StatisticDeviceDto ) event.getObject();
	}
	/**
	 * 重置查询
	 * @throws ParseException
	 */
	public void resetQuery() throws ParseException {
		selectedDto = null;
		selectedVoltage = new String[] {"35","110","220","500"};
		unitType = 0 ;
		statisticTableDto = resetDispatchDeviceDto();;
	}

	/**
	 * 重置查询和重新统计
	 */
	private List<StatisticDeviceDto> resetDispatchDeviceDto() {
		List<PrimaryDeviceCount> dispatchList = queryM.findDispatchPrimaryDeviceCount(getCurrentYear());
		if(dispatchList.isEmpty()) {
			return new ArrayList<StatisticDeviceDto>();
		}
		List<StatisticDeviceDto> list = filterTableDto(dispatchList,dispatchType);
		return list;
	}
	/**
	 * 重置查询和重新统计
	 */
	private List<StatisticDeviceDto> resetMaintenanceDeviceDto() {
		List<PrimaryDeviceCount> maintenanceList = queryM.findMaintenancePrimaryDeviceCount(getCurrentYear());
		if(maintenanceList.isEmpty()) {
			return new ArrayList<StatisticDeviceDto>();
		}
		List<StatisticDeviceDto> list = filterTableDto(maintenanceList,maintenanceType);
		return list;
	}


	/**
	 * 初始化调管范围的table
	 */
	private  List<StatisticDeviceDto>  initDispatchDeviceTable() {
		List<PrimaryDeviceCount> dispatchList = queryM.findDispatchPrimaryDeviceCount(getCurrentYear());
		if(dispatchList.isEmpty()) {
			updateTime = DateUtil.getStringDate(new Date(), DateUtil.pattern_ymd);
			return new ArrayList<PrimaryDeviceCountController.StatisticDeviceDto>();
		}else {
			updateTime = DateUtil.getStringDate(dispatchList.get(0).getStatisticTime(), DateUtil.pattern_ymd);
			List<StatisticDeviceDto> list = filterTableDto(dispatchList,dispatchType);
			return list;
		}

	}
	/**
	 * 当前年份
	 * @return
	 */
	public int getCurrentYear(){
		Date d = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		return c.get(Calendar.YEAR);
	}
	/**
	 * 汇总
	 * @param type
	 * @return
	 */
	public String getSummary(String type) {
		if(statisticTableDto==null) {
			return "";
		}
		Byte deviceType = Byte.valueOf(type);
		float c = 0;
		for (StatisticDeviceDto dto : statisticTableDto) {
			if (PrimaryDeviceCountPersistenceManager.StatisticType.substation.getType()==deviceType) {
				if(dto.getStationCount()!=null) c+=dto.getStationCount();
			}else if(PrimaryDeviceCountPersistenceManager.StatisticType.busbarsection.getType()==deviceType){
				if(dto.getBusbarsectionCount()!=null) c+=dto.getBusbarsectionCount();
			}else if(PrimaryDeviceCountPersistenceManager.StatisticType.line.getType()==deviceType){
				if(dto.getLineCount()!=null) c+=dto.getLineCount();
			}else if(PrimaryDeviceCountPersistenceManager.StatisticType.powertransformer.getType()==deviceType){
				if(dto.getPowerTransformerCount()!=null) c+=dto.getPowerTransformerCount();
			}else if(PrimaryDeviceCountPersistenceManager.StatisticType.breaker.getType()==deviceType){
				if(dto.getBreakerCount()!=null) c+=dto.getBreakerCount();
			}else if(PrimaryDeviceCountPersistenceManager.StatisticType.generatingunit.getType()==deviceType) {
				if(dto.getGeneratorCount()!=null) c+=dto.getGeneratorCount();
			}else  {
				if(dto.getSummary()!=null) c+=Float.valueOf(dto.getSummary());
			}
		}
		return String.valueOf(c).replace(".0", "");
	}





	/**
	 * 更新数量change事件
	 * @param type
	 */
	public void onChange(String type) {
		Byte operate = 1;
		Byte deviceType = Byte.valueOf(type);
		Long statisticCount = null ;
		if (PrimaryDeviceCountPersistenceManager.StatisticType.substation.getType()==deviceType) {
			statisticCount = selectedDto.getStationCount();
		}else if(PrimaryDeviceCountPersistenceManager.StatisticType.busbarsection.getType()==deviceType){
			statisticCount = selectedDto.getBusbarsectionCount();
		}else if(PrimaryDeviceCountPersistenceManager.StatisticType.line.getType()==deviceType){
			statisticCount = selectedDto.getLineCount();
		}else if(PrimaryDeviceCountPersistenceManager.StatisticType.powertransformer.getType()==deviceType){
			statisticCount = selectedDto.getPowerTransformerCount();
		}else if(PrimaryDeviceCountPersistenceManager.StatisticType.breaker.getType()==deviceType){
			statisticCount = selectedDto.getBreakerCount();
		}else if(PrimaryDeviceCountPersistenceManager.StatisticType.generatingunit.getType()==deviceType) {
			statisticCount = selectedDto.getGeneratorCount();
		}
		PrimaryDeviceCount c = queryM.findPrimaryDeviceCountByDeviceTypeUnitUnitTypeVoltageLevel(Byte.valueOf(type)
				, selectedDto.getUnit(),selectedDto.getUnitType(),Float.valueOf(selectedDto.getVoltageLevel()));
		if(c != null) {
			c.setStatisticCount(statisticCount);
			c.setOperateStatus(operate);
			presistenceM.update(c);
		}else {
			c = new PrimaryDeviceCount();
			c.setOperateStatus(operate);
			c.setStatisticCount(statisticCount);
			c.setStatisticTime(new Date());
			c.setStatisticType(deviceType);
			c.setUnitName(selectedDto.getUnit());
			c.setUnitType(selectedDto.getUnitType());
			c.setVoltageLevel(Float.valueOf(selectedDto.getVoltageLevel()));
			presistenceM.save(c);
		}
		selectedDto.setSummary(getRowSummary(selectedDto));
	}
	/**
	 * 只展示固定几个电压等级
	 * @param type
	 * @param currentDeviceCounts2
	 * @return
	 */
	private List<StatisticDeviceDto> filterTableDto(List<PrimaryDeviceCount> currentDeviceCounts, Byte type) {
		List<StatisticDeviceDto>  list  = statisticTableDto(currentDeviceCounts,type);
		List<StatisticDeviceDto>  listReturn = new ArrayList<StatisticDeviceDto>();
		for (StatisticDeviceDto statistic : list) {
			if(voltageLevels.contains(Float.valueOf(statistic.getVoltageLevel()))) {
				listReturn.add(statistic);
			}
		}
		sortStatisticDeviceDtoList(listReturn);
		return listReturn;
	}
	/**
	 * 根据一次设备数量集合统计调度dto
	 * @param type
	 * @param currenDeviceCounts
	 * @return
	 */
	private List<StatisticDeviceDto> statisticTableDto(List<PrimaryDeviceCount> currentDeviceCounts, Byte type) {
		//该map对传来的集合进行整理  key为单位-电压等级  value为 key对应的各个设备统计
		Map<String,List<PrimaryDeviceCount>> deviceMap = getDeviceMap(currentDeviceCounts,type);
		List<StatisticDeviceDto>  deviceDto = new ArrayList<StatisticDeviceDto>();
		for(Entry<String,List<PrimaryDeviceCount>> entry:deviceMap.entrySet()) {
			StatisticDeviceDto dto = new StatisticDeviceDto();
			String[] key = entry.getKey().split("-");//包含单位和电压等级
			dto.setId(ObjectId.get().toString());
			dto.setUnitType(type);
			dto.setUnit(key[0]);
			DecimalFormat df = new DecimalFormat("###.####");
			dto.setVoltageLevel(df.format(Float.valueOf(key[1])));
			for (PrimaryDeviceCount count : entry.getValue()) {
				switch(count.getStatisticType()) {
					case 0:{
						dto.setStationCount(count.getStatisticCount());
						break;
					}
					case 1:{
						dto.setBusbarsectionCount(count.getStatisticCount());
						break;
					}
					case 2:{
						dto.setLineCount(count.getStatisticCount());
						break;
					}
					case 3:{
						dto.setPowerTransformerCount(count.getStatisticCount());
						break;
					}
					case 4:{
						dto.setBreakerCount(count.getStatisticCount());
						break;
					}
					case 5:{
						dto.setGeneratorCount(count.getStatisticCount());
					}
				}//switch结束
			}//内层for结束
			dto.setSummary(getRowSummary(dto));//每个dto  set完每种设备的数量 再去汇总    这一行设备数量进行相加
			deviceDto.add(dto);
		}
		sortStatisticDeviceDtoList(deviceDto);
		return deviceDto;
	}
	private String getRowSummary(StatisticDeviceDto dto) {
		float c = 0;
		if(dto.getStationCount()!=null) {
			c+=dto.getStationCount();
		}
		if(dto.getBusbarsectionCount()!=null) {
			c+=dto.getBusbarsectionCount();
		}
		if(dto.getLineCount()!=null) {
			c+=dto.getLineCount();
		}
		if(dto.getPowerTransformerCount()!=null) {
			c+=dto.getPowerTransformerCount();
		}
		if(dto.getBreakerCount()!=null) {
			c+=dto.getBreakerCount();
		}
		if(dto.getGeneratorCount()!=null) {
			c+=dto.getGeneratorCount();
		}
		return String.valueOf(c).replace(".0", "");
	}

	private void sortStatisticDeviceDtoList(List<StatisticDeviceDto> protectionList) {
		Collections.sort(protectionList, new Comparator<StatisticDeviceDto>() {
			@Override
			public int compare(StatisticDeviceDto pro1, StatisticDeviceDto pro2) {
				String name1 = pro1.getUnit();
				String name2 = pro2.getUnit();
				if (StringUtils.isEmpty(name1) || StringUtils.isEmpty(name2)) {
					return 1;
				}
				int res = name1.compareTo(name2);
				if (res == 0) {
					double voltageOne  = (Double.valueOf(pro1.getVoltageLevel()));
					double voltageTwo = (Double.valueOf(pro2.getVoltageLevel()));
					double result = voltageOne - voltageTwo;
					if(result>0) res = 1;
					else if(result == 0.0) res = 0;
					else if(result<0) res = -1;
				}
				return res;
			}
		});
	}


	/**
	 * 根据一次设备统计集合整理成 封装dto所需的map
	 * @param currentDeviceCounts
	 * @return
	 */
	private Map<String, List<PrimaryDeviceCount>> getDeviceMap(List<PrimaryDeviceCount> currentDeviceCounts,byte unitType) {
		Map<String,List<PrimaryDeviceCount>> deviceMap = new HashMap<String,List<PrimaryDeviceCount>>();
		for (PrimaryDeviceCount primaryDeviceCount : currentDeviceCounts) {//抽离出对应单位的数据
			if(primaryDeviceCount.getUnitType()!=unitType) {
				continue;
			}
			String key = primaryDeviceCount.getUnitName()+"-"+String.valueOf(primaryDeviceCount.getVoltageLevel());
			List<PrimaryDeviceCount> deviceCounts = deviceMap.get(key);
			if(deviceCounts==null) {
				deviceCounts = new ArrayList<PrimaryDeviceCount>();
				deviceCounts.add(primaryDeviceCount);
				deviceMap.put(key, deviceCounts);
			}else {
				deviceCounts.add(primaryDeviceCount);
			}
			updateTime = DateUtil.getStringDate(primaryDeviceCount.getStatisticTime(), DateUtil.pattern_ymd);
		}
		return deviceMap;
	}
	/**
	 * 设备dto
	 * @author xu
	 *
	 */
	public class StatisticDeviceDto  {

		private String id;

		private String unit;

		private Byte unitType;

		private String voltageLevel;

		private Long stationCount;

		private Long busbarsectionCount;

		private Long lineCount;

		private Long powerTransformerCount;

		private Long breakerCount;

		private Long generatorCount;

		private String summary;


		public String getUnit() {
			return unit;
		}

		public void setUnit(String unit) {
			this.unit = unit;
		}

		public String getVoltageLevel() {
			return voltageLevel;
		}

		public void setVoltageLevel(String voltageLevel) {
			this.voltageLevel = voltageLevel;
		}

		public Long getStationCount() {
			return stationCount;
		}

		public void setStationCount(Long stationCount) {
			this.stationCount = stationCount;
		}

		public Long getBusbarsectionCount() {
			return busbarsectionCount;
		}

		public void setBusbarsectionCount(Long busbarsectionCount) {
			this.busbarsectionCount = busbarsectionCount;
		}

		public Long getLineCount() {
			return lineCount;
		}

		public void setLineCount(Long lineCount) {
			this.lineCount = lineCount;
		}

		public Long getPowerTransformerCount() {
			return powerTransformerCount;
		}

		public void setPowerTransformerCount(Long powerTransformerCount) {
			this.powerTransformerCount = powerTransformerCount;
		}

		public Long getBreakerCount() {
			return breakerCount;
		}

		public void setBreakerCount(Long breakerCount) {
			this.breakerCount = breakerCount;
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public Byte getUnitType() {
			return unitType;
		}

		public void setUnitType(Byte unitType) {
			this.unitType = unitType;
		}

		public Long getGeneratorCount() {
			return generatorCount;
		}

		public void setGeneratorCount(Long generatorCount) {
			this.generatorCount = generatorCount;
		}

		public String getSummary() {
			return summary;
		}

		public void setSummary(String summary) {
			this.summary = summary;
		}




	}

	public List<PrimaryDeviceCount> getCurrentDeviceCounts() {
		return currentDeviceCounts;
	}

	public void setCurrentDeviceCounts(List<PrimaryDeviceCount> currentDeviceCounts) {
		this.currentDeviceCounts = currentDeviceCounts;
	}
	public String getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(String updateTime) {
		this.updateTime = updateTime;
	}

	public List<Float> getVoltageLevels() {
		return voltageLevels;
	}

	public void setVoltageLevels(List<Float> voltageLevels) {
		this.voltageLevels = voltageLevels;
	}
	public Byte getUnitType() {
		return unitType;
	}

	public void setUnitType(Byte unitType) {
		this.unitType = unitType;
	}

	public List<StatisticDeviceDto> getStatisticTableDto() {
		return statisticTableDto;
	}

	public void setStatisticTableDto(List<StatisticDeviceDto> statisticTableDto) {
		this.statisticTableDto = statisticTableDto;
	}

	public String getQueryYear() {
		return queryYear;
	}

	public void setQueryYear(String queryYear) {
		this.queryYear = queryYear;
	}

	public StatisticDeviceDto getSelectedDto() {
		return selectedDto;
	}

	public void setSelectedDto(StatisticDeviceDto selectedDto) {
		this.selectedDto = selectedDto;
	}

	public String[] getSelectedVoltage() {
		return selectedVoltage;
	}

	public void setSelectedVoltage(String[] selectedVoltage) {
		this.selectedVoltage = selectedVoltage;
	}

	public Boolean getReStatisticStatus() {
		return reStatisticStatus;
	}

	public void setReStatisticStatus(Boolean reStatisticStatus) {
		this.reStatisticStatus = reStatisticStatus;
	}

}
